import java.util.Iterator;
import java.io.*;
import java.util.ArrayList;
import org.jdom.*;
import org.jdom.filter.ElementFilter;
import org.jdom.input.*;

/**
 * <p><code>CheatSheetBuilder</code> builds an array that holds 
 * all the XSS cheat sheet payloads.
 * </p>
 * 
 * @author Ofer Rotberg
 * @version 1.0
 */
public class CheatSheetBuilder {

	private ArrayList<XssAttack> xssPayloads = null;

	public CheatSheetBuilder(String filename) throws JDOMException, IOException{
		this.xssPayloads = new ArrayList<XssAttack>();
		//buildXssArrayFromXml(filename);
		buildXssArrayFromTxt(filename);
	}

	private void buildXssArrayFromTxt(String filename) throws IOException{
		//open file
		BufferedReader br = new BufferedReader(new FileReader(filename));
		//read file
		String current = br.readLine();
		//parse file and put elements in array
		while(current!=null){
			XssAttack xa = new XssAttack(null,current);
			xssPayloads.add(xa);
			current = br.readLine();
		}
	}
	private void buildXssArrayFromXml(String filename) throws JDOMException, IOException{

		//prepare SAX parser
		SAXBuilder builder = null;
		builder = new SAXBuilder();
		Document doc = builder.build(filename);

		//extract payloads
		Iterator<Element> iter = doc.getDescendants(new ElementFilter("attack"));

		while (iter.hasNext()){
			Element elem = iter.next();
			Element desc = elem.getChild("desc");
			Element code = elem.getChild("code");	
			Element browser = elem.getChild("browser");
			String browserSupport = browser.getText();
			int end = browserSupport.indexOf("FF");
			int start = end-1;
			if (end>-1)
				while (browserSupport.charAt(start)!='<')
					start-=1;
			if	 ((end>-1) && (! (browserSupport.substring(start,end).indexOf("ns")>-1) )){
				XssAttack xa = new XssAttack(desc.getText(),code.getText());
				this.xssPayloads.add(xa);
			}
		}
	}

	public ArrayList<XssAttack> getXssPayloads() {
		return xssPayloads;
	}
}
